var logger = require('../service/Logger');
var entity = require('../entity');
var Faction = entity.Faction;
var Activity = entity.Activity;
var Relation = entity.Relation;
var User = entity.User;
var redisManager = require('./redisManager');
var relation = require('./relation');
var userProxy = require('./user');
var factionMemberProxy = require('./factionmember');
var needle = require('needle');
/**
 * 创建新的活动
 * @param name
 * @param startTime
 * @param location
 * @param remark
 * @param creator
 * @param callback
 */
exports.newAndSave = function(name, startTime,
                              location, remark,
                              creator, hasContact,
                              hasBusiness,
                              factionId, score, type, callback){
    var activity = new Activity();
    activity.name = name;
    activity.startTime = startTime? new Date(Date.parse(startTime.replace(/-/g,   "/"))) : new Date();
    activity.location = location;
    activity.remark = remark;
    activity.creator = creator;
    activity.hasContact = hasContact;
    activity.hasBusiness = hasBusiness;
    activity.score = score || 5;
    activity.actType = type || 'fanju';
    activity.joinCode = _generateInviteCode();
    if(factionId){
        activity.belongFaction = factionId;
    }
    activity.save(function(err, act){
        if(err) return callback(err);
        callback(err, act);
    });
}
function _generateInviteCode(){
    var code = Math.round(Math.random()*10000);
    code = code<1000?code*10:code;
    return code;
}
exports.updateAct = function(actId, name, startTime, location, remark,
                             creator, hasContact, hasBusiness, factionId, score, type, callback){
    Activity.update({_id: actId}, {$set :{
        name: name,
        startTime: startTime? new Date(Date.parse(startTime.replace(/-/g,   "/"))) : new Date(),
        location: location,
        remark: remark
    }}, {}, function(err, resp){
        callback(err, resp);
    })
}
/**
 * 增加一个参与人
 * @param id
 * @param user
 * @param callback
 */
exports.addAtend = function(id, user, callback){
    redisManager.isInAttends(id, user.id, function(err, resp){
        if(resp == 1){
            return callback(null, {already: 'already'});
        }else{
            Activity.findOne({_id: id}, function(err, act){
                //圈活动
                if(act.belongFaction){
                    // 验证是否圈内人
                    var factionId = act.belongFaction.toHexString();
                    redisManager.isInFaction(factionId, user.id, function(err, isIn){
                        console.log(isIn)
                        if(isIn){
                            var max = 110, min = 20;
                            var score = Math.floor(min+Math.random()*(max-min));
                            user.score = score;
                            _addUserIntoAct(act, user, function(err, data){
                                //获得随即积分
                                factionMemberProxy.addScore(factionId, user.id, score, function(err, resp){
                                    if(err) logger.error(err.message);
                                    redisManager.addAttendActScore(id, user.id, score, function(err, resp){
                                        console.log('User ['+user.id+'] in faction ['+factionId+'] add score:'+score);
                                    })
                                });
                                data.score = score;
                                return callback(err, data);
                            });
                        }else{
                            return callback(null, {outside:'outside'});
                        }
                    })

                }else{
                    _addUserIntoAct(act, user, function(err, data){
                        return callback(err, data)
                    });
                }
            });
        }
    })
}
function _addUserIntoAct(act, user, callback){
    //创建是否是本人
    if(act.creator.id === user.id){
        return callback(null, {already: 'already'});//TODO:
    }
    var attends = act.attends;
    var attender = {
        id: user.id,
        name: user.name,
        gender: user.gender,
        remark: user.remark,
        score: user.score || 0,
        time: new Date(),
        No: attends.length + 1
    }
    /*for(var i= 0,len=attends.length; i<len; i++){//TODO: 使用缓存判断
        if(attends[i].id === user.id){
            return callback(null, {already: 'already'});
        }
    }*/
    redisManager.addAttendSet(act._id, user.id, function(err, resp){
        logger.debug('add user:['+user.id+'] to act:['+act._id+'] set cache ');
    });
    redisManager.setAttendActNo(act._id, user.id, attender.No, function(err, resp){
        if(err) return logger.error(err)
        logger.debug('user:['+user.id+'] in act:['+act._id+'] No:'+attender.No);
    });
    act.attends.push(attender);
    act.attendNum = act.attendNum + 1;
    act.save(function(err, data){
        if(err) return callback(err);
        var attends = data.attends;
            attends.push(data.creator);
        var postData = {
            attends: attends,
            userId: user.id
        }
        // 给所有与会人增加关系
        relationBuilder.send(postData);
        callback(err, data);
    });
}
/**
 * 取消参加
 * @param id
 * @param user
 * @param callback
 */
exports.cancelAttend = function(id, user, callback){
    Activity.findOne({_id: id}, function(err, act){
        if(err) return callback(err);
        var attends = act.attends;
        var tmp = [];
        var hasAttended = false;
        for(var i= 0,len=attends.length; i<len; i++){
            if(attends[i].id !== user.id){
                tmp.push(attends[i]);
            }else{
                hasAttended = true;
            }
        }
        if(!hasAttended){
            return callback(err, null);
        }
        act.attends = tmp;
        act.attendNum = act.attendNum - 1;
        act.save(function(err, data){
            if(err) return callback(err);
            relation.subtractRelationWeight(act.creator.id, user.id, 1, function(err, data){
                if(err) logger.error(err.message);
                logger.debug('['+act.creator.name+'] and ['+user.name+'] subtract relation ---- '+1);
            });
            callback(err, data);
        });
    })
}

/**
 * 发起人活动列表
 * @param userid
 * @param callback
 *
 */
exports.pageMyActlist = function(userid, pageNo, pageSize, callback){
    var start = (pageNo - 1)*pageSize;
    Activity.find({$or:[{'creator.id': userid}, {attends:{$elemMatch:{id:userid}}}] })
        .sort({startTime:-1})
        .skip(start)
        .limit(pageSize)
        .exec(function(err, acts){
        callback(err, acts);
    });
}

exports.getAllMyActs = function(userid, callback){
    Activity.find({$or:[{'creator.id': userid}, {attends:{$elemMatch:{id:userid}}}] }, '_id name startTime')
        .exec(function(err, acts){
        callback(err, acts);
    })
}

/**
 *
 * @param actId
 * @param callback
 */
exports.setExpired = function(actId, callback){
    Activity.findOne({_id: actId}).exec(function(err, act){
        act.hasExpired = true;
        act.save(function(err, data){
            callback(err, data);
        })
    })
}
/**
 * 根据邀请码加入
 * @param joinCode
 * @param fromOpenId
 * @param callback
 */
exports.joinActivity = function(joinCode, user, callback){
    var obj = limitStackMap.get(joinCode);
    if(obj && new Date().getTime() < obj.vaildTime){
        this.addAtend(obj.actId, user, function(err, data){
            logger.debug('user :['+user.id+'] join act by code :['+joinCode+']')
            if(data.score){
                //增加积分
                userProxy.increaseScore(user, data.score, function(err, user){})
            }
            callback(err, data);
        });
    }else{
        callback(null, null);
    }
}
/**
 *
 * @param factionId
 * @param callback
 */
exports.findByFaction = function(factionId, callback){
    Activity.find({belongFaction: factionId})
        .sort({startTime:-1})
        .exec(function(err, acts){
        callback(err, acts);
    })
}

exports.pageFactionActs = function(factionId, pageNo, pageSize, callback){
    var start = (pageNo - 1)*pageSize;
    Activity.find({belongFaction: factionId})
        .sort({startTime: -1})
        .skip(start)
        .limit(pageSize)
        .exec(function(err, acts){
            callback(err, acts);
        })
}

exports.getActivityById = function(id, callback){
    Activity.findOne({_id: id})
        .populate('belongFaction')
        .exec(function(err, act){
            callback(err, act);
    });
}

exports.removeById = function(id, callback){
    Activity.remove({_id: id}, callback)
}
